package com.hns.can.safety.service;

import com.hns.can.common.entity.BaseEntity;
import com.hns.can.common.formula.FillCodeDscValue;
import com.hns.can.safety.entity.BaseBlackArchivesInfoEntity;
import com.hns.can.safety.vo.BaseBlackArchivesInfoVo;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.mybatis.Pagination;
import com.hns.frame.service.CommonService;
import com.hns.tool.pub.DateTool;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.UtilConfig;
import com.hns.tool.pub.UtilString;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 黑点模型
 *
 * @version Revision 2.0.0
 * @author:jeffxu
 * @email:835264047@qq.com
 */
@Service
public class BaseBlackArchivesInfoService extends CommonService {

    private static final Logger logger = LoggerFactory.getLogger(BaseBlackArchivesInfoService.class);

    @Autowired
    private FillCodeDscValue codeDscValue;

    /**
     * 获取黑点档案信息列表（分页）
     *
     * @param vo
     * @return
     */
    @Transactional
    public Pagination searchBaseBlackArchivesInfoPage(BaseBlackArchivesInfoVo vo) {
        Pagination page = this.myBatisPage("baseBlackArchivesInfo.searchBaseBlackArchivesInfoCnt",
                "baseBlackArchivesInfo.searchBaseBlackArchivesInfoList", vo, BaseBlackArchivesInfoEntity.class);
        return page;
    }

    /**
     * 获取黑点档案信息列表
     *
     * @param vo
     * @return
     */
    @Transactional
    public List<BaseEntity> getBaseBlackArchivesInfoList(BaseBlackArchivesInfoVo vo) {
        List<BaseEntity> list = PubUtil.convertListMapToObject(
                sqlMapDao.selectList("baseBlackArchivesInfo.searchBaseBlackArchivesInfoList", vo), BaseBlackArchivesInfoEntity.class);

        //解析代码描述信息
        Map<String, String> map = new HashMap<String, String>();
        map.put("blackNature", "BLAK0000");
        codeDscValue.fillCodeDscValue(list, map);
        return list;
    }

    /**
     * 通过id获取黑点档案信息
     *
     * @param rcrdId
     * @return
     */
    @Transactional
    public BaseBlackArchivesInfoEntity getBaseBlackArchivesInfoById(String rcrdId) {
        BaseBlackArchivesInfoEntity entity = this.commonEntityDao.find(rcrdId, BaseBlackArchivesInfoEntity.class);
        return entity;
    }

    /**
     * 通过id删除黑点档案信息
     *
     * @param rcrdId
     */
    @Transactional
    public void delBaseBlackArchivesInfoById(String rcrdId) {
        BaseBlackArchivesInfoEntity entity = this.commonEntityDao.find(rcrdId, BaseBlackArchivesInfoEntity.class);
        this.commonEntityDao.delete(entity);
    }

    /**
     * 添加或编辑黑点档案信息
     *
     * @param entity
     */
    @Transactional
    public void addOrUptBaseBlackArchivesInfo(BaseBlackArchivesInfoEntity entity) {
        //# 验证规则
        checkAddOrUpt(entity);

        if (PubUtil.isEmpty(entity.getRcrdId())) {//添加
            entity.setRcrdId(UtilString.getUUID());
            this.commonEntityDao.save(entity);
        } else {//编辑
            //数据整理
            BaseBlackArchivesInfoEntity entity1 = this.commonEntityDao.find(
                    entity.getRcrdId(), BaseBlackArchivesInfoEntity.class);
            entity.setCrtUser(entity1.getCrtUser());
            entity.setCrtTime(entity1.getCrtTime());
            this.commonEntityDao.update(entity);
        }
    }

    /**
     * 验证规则
     *
     * @param entity
     */
    private void checkAddOrUpt(BaseBlackArchivesInfoEntity entity) {
        //黑点名称
        if (PubUtil.isNotEmpty(entity.getBlackName())) {
            this.check("baseBlackArchivesInfo.checkBlackName", entity, "您输入的黑点名称已经存在！");
        }
    }

    /**
     * 这里这里用的是MultipartFile[] myfiles参数,所以前台就要用<input type="file" name="myfiles"/>
     */
    public String fileUpload(
            @RequestParam MultipartFile[] myfiles, String uploadPath,
            HttpServletRequest request, HttpServletResponse response) throws IOException {
        //如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中
        //这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断/upload是否存在,不存在会自动创建
//        String realPath = request.getSession().getServletContext().getRealPath("/") + uploadPath;
        String realPath = UtilConfig.getString("upload_file_base_path") + uploadPath;//自定义图片保存路径

        //上传文件的原名(即上传前的文件名字)
        String originalFilename = null;
        //保存的文件名
        String saveFileName = "";

        //设置响应给前台内容的数据格式
        response.setContentType("text/plain; charset=UTF-8");
        //设置响应给前台内容的PrintWriter对象
        PrintWriter out = response.getWriter();
        //上传文件的原名(即上传前的文件名字)
        //如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解
        //如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且要指定@RequestParam注解
        //上传多个文件时,前台表单中的所有<input type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件
        for (MultipartFile myfile : myfiles) {
            if (myfile.isEmpty()) {
                throw new BusinessException(MsgType.WARN.getFlag(), "请选择文件后上传");
            } else {
//                System.out.println(URLDecoder.decode(myfile.getOriginalFilename(), "UTF-8"));
                originalFilename = new String(myfile.getOriginalFilename().getBytes("ISO-8859-1"), "utf-8");
                saveFileName = DateTool.getCurrentSysDate("yyyyMMddHHmmss") + originalFilename.substring(originalFilename.lastIndexOf("."));

                try {
                    //这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
                    //此处也可以使用Spring提供的MultipartFile.transferTo(File dest)方法实现文件的上传
                    FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, saveFileName));
                } catch (IOException e) {
                    logger.error("文件[" + originalFilename + "]上传失败,堆栈轨迹如下", e);
                    out.print("1文件上传失败，请重试！！");
                    out.flush();
                    return null;
                }
            }
        }
        out.print("0" + uploadPath + "\\" + saveFileName);
        out.flush();

        return null;
    }

    /**
     * 预览，获取图片流
     *
     * @param uploadPath
     * @param request
     * @param response
     * @return: void
     */
    public void readImage(String uploadPath, HttpServletRequest request, HttpServletResponse response) throws Exception {
//        String imagePath = request.getSession().getServletContext().getRealPath("/") + uploadPath;
        String imagePath = UtilConfig.getString("upload_file_base_path") + uploadPath;//自定义图片保存路径

        imagePath = new String(imagePath.getBytes("ISO-8859-1"), "utf-8");
        try {
            File file = new File(imagePath);
            if (file.exists()) {
                DataOutputStream temps = new DataOutputStream(response.getOutputStream());
                DataInputStream in = new DataInputStream(new FileInputStream(imagePath));
                byte[] b = new byte[2048];
                while ((in.read(b)) != -1) {
                    temps.write(b);
                    temps.flush();
                }
                in.close();
                temps.close();
            }
        } catch (Exception e) {
            logger.error("读取图片错误:" + e.getMessage(), e);
        }
    }
}
